import { getNewCartGoods, mergeLocalCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'

// 购物车
export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品列表
      list: []
    }
  },

  getters: {
    // 有效商品列表
    validList (state) {
      return state.list.filter(good => good.stock > 0 && good.isEffective)
    },

    // 有效商品总件数
    validTotal (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },

    // 有效商品的总价格
    validAmount (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count * c.nowPrice * 100, 0) / 100
    },

    // 无效商品列表
    invalidList (state) {
      return state.list.filter(good => good.stock <= 0 || !good.isEffective)
    },

    // 已选商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },

    // 已选商品总件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },

    // 已选商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + Math.round(c.nowPrice * 100) * c.count, 0) / 100
    },

    // 是否全选
    isCheckBox (state, getters) {
      // 已选择的数据长度 === 有效商品长度
      return getters.validList.length !== 0 && getters.selectedList.length === getters.validList.length
    }
  },

  // id skuId name attrsName picture price nowPrice selected stock count isEffective

  mutations: {
    // 商品加入购物车
    insertCart (state, payload) {
      // 是否出现相同商品 有：查询数据，合并累加到payload，保存在最新位置 无：保存在最前面
      const index = state.list.findIndex(good => good.skuId === payload.skuId)
      if (index >= 0) {
        payload.count = state.list[index].count + payload.count
        state.list.splice(index, 1) // 删除原来
      }
      state.list.unshift(payload) // 添加新数据
    },

    // 修改本地某一条数据
    updataCart (state, payload) {
      // 根据skuid找到要修改的商品
      const updateGoods = state.list.find(item => item.skuId === payload.skuId)
      for (const k in payload) {
        if (payload[k] !== undefined && payload[k] !== null && payload[k] !== '') {
          updateGoods[k] = payload[k]
        }
      }
    },

    // 删除购物车商品
    deleteCart (state, payload) {
      const index = state.list.findIndex(item => item.skuId === payload)
      state.list.splice(index, 1)
    },

    // 设置购物车
    setCart (state, payload) {
      state.list = payload
    }
  },

  actions: {
    // 加入购物车
    insertCart (ctx, payload) {
      return new Promise((resolve, reject) => {
        // 已登录  未登录 根据user模块中的token信息判断
        if (ctx.rootState.user.profile.token) {
          insertCart({ skuId: payload.skuId, count: payload.count }).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('insertCart', payload)
          resolve()
        }
      })
    },

    // 获取最新商品信息，更新数据
    findCart (ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          findCartList().then(data => {
            ctx.commit('setCart', data.result)
          })
          resolve()
        } else {
          // 同时发送多个请求 （根据本地商品种类） 等所有的请求成功 一并修改
          // promise.all(数组).then(dataList => {}) 同时发送请求
          // promise.race() 谁先结束，结果就是谁
          const promiseArr = ctx.state.list.map(goods => {
            return getNewCartGoods(goods.skuId)
          })
          Promise.all(promiseArr).then(dataList => {
            console.log(dataList)
            dataList.forEach((data, i) => {
              ctx.commit('updataCart', { skuId: ctx.state.list[i].skuId, ...data.result })
            })
            resolve()
          })
        }
      })
    },

    // 删除购物车商品
    deleteCart (ctx, skuId) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          deleteCart([skuId]).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          ctx.commit('deleteCart', skuId)
          resolve()
        }
      })
    },

    // 修改购物车 （选中状态、数量）
    updataCart (ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          updateCart(payload).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          ctx.commit('updataCart', payload)
          resolve()
        }
      })
    },

    // 全选，取消全选
    checkAllCart (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          const ids = ctx.getters.validList.map(item => item.skuId)
          checkAllCart({ selected, ids }).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          ctx.getters.validList.forEach(goods => {
            ctx.commit('updataCart', { skuId: goods.skuId, selected })
          })
          resolve()
        }
      })
    },

    // 批量删除
    bartchDeleteCar (ctx, isClear) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 获取所选商品的所有sku集合
          const ids = ctx.getters[isClear ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCart(ids).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          ctx.getters[isClear ? 'invalidList' : 'selectedList'].forEach(goods => {
            ctx.commit('deleteCart', goods.skuId)
          })
          resolve()
        }
      })
    },

    // 修改规格
    updateCartSku (ctx, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          /*
            1、找到旧数据
            2、删除旧数据
            3、根据新、旧数据，合成一条新的数据
            4、添加新的商品
          */
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          deleteCart([oldGoods.skuId]).then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(() => {
            return findCartList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          /*
            1、找到旧数据
            2、删除旧数据
            3、根据新、旧数据，合成一条新的数据
            4、添加新的商品
          */
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          ctx.commit('deleteCart', oldSkuId)
          const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          ctx.commit('insertCart', newGoods)
          resolve()
        }
      })
    },

    // 合并购物车
    async margeCart (ctx) {
      const cartList = ctx.state.list.map(item => {
        return { skuId: item.skuId, selected: item.selected, count: item.count }
      })

      await mergeLocalCart(cartList)
      // 合并成功   清空本地
      ctx.commit('setCart', [])
    }

  }
}
